package org.ssssssss.magicapi.ws;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.ssssssss.magicapi.core.service.MagicAPIService;
import org.tio.websocket.server.WsServerStarter;
import org.tio.core.TioConfig;
import org.tio.server.TioServerConfig;

import java.io.IOException;

public class R2rWsServerStarter {
	
	private static MagicAPIService service;
	
	public static void setService(MagicAPIService service) {
		R2rWsServerStarter.service = service;
	}
	public static MagicAPIService getService() {
		return service;
	}
	
	public static TioConfig getConfig() {
		return serverTioConfig;
	}
	
	private static final Logger logger = LoggerFactory.getLogger(R2rWsServerStarter.class);
	private static WsServerStarter wsServerStarter;
	private static TioServerConfig serverTioConfig;
	
	public static void start(int port) throws IOException {
		logger.info("启动WebsoketServer");
		wsServerStarter = new WsServerStarter(port, R2rWsMsgHandler.me);
		serverTioConfig = wsServerStarter.getTioServerConfig();
		serverTioConfig.setName(R2rWsServerConfig.PROTOCOL_NAME);
		serverTioConfig.setTioServerListener(R2rWsServerAioListener.me);

		//设置ip监控
		//serverTioConfig.setIpStatListener(R2rWsIpStatListener.me);
		//设置ip统计时间段
		//serverTioConfig.ipStats.addDurations(R2rWsServerConfig.IpStatDuration.IPSTAT_DURATIONS);
		
		//设置心跳超时时间
		serverTioConfig.setHeartbeatTimeout(R2rWsServerConfig.HEARTBEAT_TIMEOUT);
		
//		if (P.getInt("ws.use.ssl", 1) == 1) {
//			//如果你希望通过wss来访问，就加上下面的代码吧，不过首先你得有SSL证书（证书必须和域名相匹配，否则可能访问不了ssl）
//			String keyStoreFile = "classpath:config/ssl/keystore.jks";
//			String trustStoreFile = "classpath:config/ssl/keystore.jks";
//			String keyStorePwd = "214323428310224";
//
//			serverTioConfig.useSsl(keyStoreFile, trustStoreFile, keyStorePwd);
//		}
		wsServerStarter.start();
	}
	
	public static void stop() {
		wsServerStarter.getTioServer().stop();
	}
}
